<template>
  <div>
    <TopFilter :list="topFilterList" :cols="4" @filterChange="changeHandler" @onCollapse="collapseHandle" />
    <FilterTable
      ref="table"
      columnsRef="jzyCardType"
      :columns="columns"
      :fetchapi="fetchApi"
      :params="fetchParams"
      :datakey="'rows'"
      :isSelectColumn="false"
      :onEnterEvent="handlePartEnterEvent"
      :onRowSelectChange="handleTableSelect"
      :onColumnsChange="columns => (this.columns = columns)"
      :isExportExcel="true"
      exportFileName="配件消耗量排名.xlsx"
    >
    </FilterTable>
    <!-- 类型选择 -->
    <el-radio-group v-model="yearFilterType" style="margin: 10px 0;">
      <el-radio label="2">上年同期比</el-radio>
      <el-radio label="1">本年各期比</el-radio>
    </el-radio-group>
    <!-- 月份统计 -->
    <FilterTable
      ref="bottomTable"
      height="auto"
      :fetchapi="bottomApi"
      :params="bottomFetchParams"
      :isSelectColumn="false"
      :isToperInfo="false"
      :isColumnFilter="false"
      :columns="bottomColumns"
      :onColumnsChange="columns => (this.bottomColumns = columns)"
    ></FilterTable>
  </div>
</template>

<script>
// 数据字典/按钮权限
import { dictionary } from '@/utils/dictMixin';
import { getStroageList } from '@/api/part/partOutbound/partBreak';
import { getConsumptionRankingList } from '@/api/part/report/consumptionRanking';
import { queryPartMonthReport } from '@/api/part/partPurchase/purchaseOrder';
import { log } from 'util';
import moment from 'moment';
export default {
  name: 'CardType',
  components: {},
  mixins: [dictionary],
  data() {
    this.BaseTable = null;
    this.selectedRow = null;
    this.editData = {};
    return {
      topFilterList: this.createTopFilters(),
      columns: this.createTableColumns(),
      fetchApi: getConsumptionRankingList,
      bottomColumns: this.createBottomColumns(),
      bottomApi: queryPartMonthReport,
      selectedTableData: [],
      bottomFetchParams: { xhrAbort: true },
      yearFilterType: '1', // 下方筛选条件
      queryInfoPart: {}, // 查询年年化信息的配件信息
      tableMockData: [],
      fetchParams: { xhrAbort: true },
      actions: { visible: false, type: '', title: '' } // 弹出面板的相关信息
    };
  },
  computed: {
    // 统计数量和累计金额
    totalNumber() {
      return this.data.inventoryList.reduce((total, curr) => {
        return Number(total + Number(curr.PROFIT_LOSS_QUANTITY));
      }, 0);
    },
    totalAmount() {
      return this.data.inventoryList.reduce((total, curr) => {
        return Number(total + Number(curr.PROFIT_LOSS_QUANTITY * curr.COST_PRICE));
      }, 0);
    }
  },
  watch: {
    yearFilterType(newVal, oldVal) {
      if (this.queryInfoPart.partNo) {
        this.handlePartEnterEvent();
      }
    }
  },
  mounted() {
    let mockObj = {};
    for (let i = 0; i < 12; i++) {
      mockObj[i + 1] = i + 1;
    }
    this.tableMockData.push(mockObj);
  },
  created() {
    this.getStorage();
  },
  methods: {
    createTopFilters() {
      return [
        {
          type: 'RANGE_DATE',
          label: '出库日期',
          fieldName: 'OPERATE_DATE_START|OPERATE_DATE_END',
          initialValue: [
            moment()
              .startOf('month')
              .format('YYYY-MM-DD'),
            moment(new Date()).format('YYYY-MM-DD HH:mm:ss')
          ],
          rules: [{ required: true, message: '选择日期', trigger: 'blur' }]
        },
        {
          type: 'SELECT',
          label: '仓库',
          fieldName: 'STORAGE_CODE',
          initialValue: '',
          itemList: []
        },
        {
          type: 'SELECT',
          label: '类别',
          fieldName: 'IN_OUT_TYPE',
          initialValue: '',
          itemList: [
            { text: '销售出库', value: '82491007' },
            { text: '维修领料', value: '82491006' },
            { text: '内部领用', value: '82491009' },
            { text: '装饰出库', value: '82491025' }
          ]
        }
        // {
        //   type: 'RADIO',
        //   // label: '申请类型',
        //   style: { minWidth: '300px' },
        //   fieldName: 'radioVal',
        //   disabled: false,
        //   itemList: [
        //     { value: '1', text: '全部' },
        //     { value: '2', text: '销售出库' },
        //     { value: '3', text: '维修领料' },
        //     { value: '4', text: '内部领用' },
        //     { value: '5', text: '装饰出库' }
        //   ],
        //   initialValue: '1',
        //   selfCols: 5,
        //   change: val => {
        //     if (val == 1) {
        //       this.radioData = val;
        //       // alert(this.radioData);
        //       this.formList = this.createFormList();
        //       this.listPro = [];
        //       this.listPart = [];
        //     }
        //   }
        // }
      ];
    },
    createTableColumns() {
      return [
        {
          title: '序号',
          dataIndex: 'index',
          width: 70,
          sorter: true,
          render: props => {
            return <span>{props.row.index + 1}</span>;
          }
        },
        {
          title: '配件代码',
          dataIndex: 'PART_NO',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '开口件代码',
          dataIndex: 'OPEN_CODE',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '配件名称',
          dataIndex: 'PART_NAME',
          // dataIndex: 'PART_DESCRIPTION',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: 'ABC分类',
          dataIndex: 'ABC_TYPE',
          sorter: true,
          filter: true,
          // filterType: 'input'
          filterType: 'checkbox',
          filterItems: this.createDictList('8092'),
          dictItems: this.createDictList('8092'),
          render: props => {
            return <span>{this.createDictText(props.row.ABC_TYPE, '8092')}</span>;
          }
        },
        {
          title: '数量',
          dataIndex: 'partSum',
          sorter: true,
          filter: true,
          filterType: 'number',
          precision: 2,
          summation: true
        },
        {
          title: '含税销售金额',
          dataIndex: 'IN_OUT_TAXED_SALES_AMOUNT',
          // dataIndex: 'IN_OUT_TAXED_AMOUNT',
          sorter: true,
          filter: true,
          filterType: 'number',
          precision: 2,
          summation: true
        },
        {
          title: '账面库存',
          dataIndex: 'STOCK_QUANTITY',
          sorter: true,
          filter: true,
          filterType: 'number',
          precision: 2,
          summation: true
        },
        {
          title: '可用库存',
          dataIndex: 'USEABLE_STOCK',
          sorter: true,
          filter: true,
          filterType: 'number',
          precision: 2,
          summation: true
        }
      ];
    },
    createBottomColumns() {
      return [
        {
          title: '一月',
          dataIndex: 'outQuantity1'
        },
        {
          title: '二月',
          dataIndex: 'outQuantity2'
        },
        {
          title: '三月',
          dataIndex: 'outQuantity3'
        },
        {
          title: '四月',
          dataIndex: 'outQuantity4'
        },
        {
          title: '五月',
          dataIndex: 'outQuantity5'
        },
        {
          title: '六月',
          dataIndex: 'outQuantity6'
        },
        {
          title: '七月',
          dataIndex: 'outQuantity7'
        },
        {
          title: '八月',
          dataIndex: 'outQuantity8'
        },
        {
          title: '九月',
          dataIndex: 'outQuantity9'
        },
        {
          title: '十月',
          dataIndex: 'outQuantity10'
        },
        {
          title: '十一月',
          dataIndex: 'outQuantity11'
        },
        {
          title: '十二月',
          dataIndex: 'outQuantity12'
        }
      ];
    },
    // 配件单击或者双击
    handlePartEnterEvent(e) {
      this.bottomFetchParams.xhrAbort = true;
      let yearInfo = this.queryYearInfo();
      this.queryInfoPart = e || this.queryInfoPart;
      console.log(yearInfo);
      console.log(this.queryInfoPart);
      this.bottomFetchParams = Object.assign(this.bottomFetchParams, {
        xhrAbort: false,
        reportYear: this.yearFilterType == 1 ? yearInfo.thisYear : yearInfo.lastYear,
        partNo: this.queryInfoPart.PART_NO
      });
    },
    // 获取当前年份跟上年年份
    queryYearInfo() {
      let date = new Date();
      return {
        thisYear: date.getFullYear(),
        lastYear: date.getFullYear() - 1
      };
    },
    async getStorage() {
      const res = await getStroageList();
      this.topFilterList.find(item => item.fieldName === 'STORAGE_CODE').itemList = res.data.map(x => ({ text: x.STORAGE_NAME, value: x.STORAGE_CODE }));
    },
    addRecordHandle() {
      this.actions = { visible: true, type: 'add', title: '新增会员卡信息' };
    },
    editRecordHandle(row) {
      if (!row) return;
      this.editData = row;
      this.actions = { visible: true, type: 'edit', title: '编辑会员卡信息' };
    },
    changeHandler(val) {
      val.OPERATE_DATE_START = val.OPERATE_DATE_START ? val.OPERATE_DATE_START.split(' ')[0] + ' 00:00:00' : '';
      val.OPERATE_DATE_END = val.OPERATE_DATE_END ? val.OPERATE_DATE_END.split(' ')[0] + ' 23:59:59' : '';
      // 增加时间限制
      if (val.OPERATE_DATE_START || val.OPERATE_DATE_END) {
        let diffMonth = moment(val.OPERATE_DATE_END).diff(moment(val.OPERATE_DATE_START), 'months');
        if (diffMonth > 5) return this.$notify.warning({ title: '提示信息', message: '起止日期跨度不能超过半年' });
      }
      this.fetchParams.xhrAbort = true;
      this.fetchParams = Object.assign({ xhrAbort: false }, val);
    },
    rowSelectHandle(rows) {
      if (!rows.length) return;
      this.selectedRow = rows[0];
    },
    // 列表行项选择变化
    handleTableSelect(e) {
      this.selectedTableData = e;
    },

    // 主页面刷新
    refreshHandle() {
      this.fetchParams = { ...this.fetchParams };
    },

    // 适配 BaseTable 组件
    collapseHandle() {
      this.$nextTick(this.BaseTable.EXECUTE_RESET_HEIGHT);
    }
  }
};
</script>

<style lang="less" scoped></style>
